/**
 * 
 */

TemplateSearchPortlet = Class.extend({
	init:function() {
		this.name = "PltTemplateSearch";
		this.viewId = "PltTemplateSearch-PltTemplateSearch";
	},
	
	render: function(){
		this.bindToHandler();
		this.jsHandler().initVars();
		var ret = this.requestForResource(this.name).children();
		return ret;
	},
	
	requestForResource: function(resourceName){
		var app = SingletonFactory.getInstance(Application);
		var rm = app.getResourceManager();
		return rm.requestForResource(this.name,resourceName);
	},
	
	jsHandler : function(){
		return SingletonFactory.getInstance(TemplateSearchPortletJSHandler);
	},
	
	bindEvent: function(eleName, eventName, actionHandler)	{
		var eleToBind = this.requestForResource(eleName);
		eleToBind.bind(eventName, function(){ actionHandler(); });
		//console.log(eleToBind);
	},

	bindToHandler : function(){
		var jsHandler = this.jsHandler();
		this.bindEvent("Submit","click",jsHandler.searchCriteria);
		this.bindEvent("Reset","click",jsHandler.resetCriteria);
		this.bindEvent("Delete","click",jsHandler.deleteAll);
		this.bindEvent("CheckUnCheck","click",jsHandler.checkUnCheckAll);
		this.bindEvent("UseKw","click",jsHandler.confirmAddFromTemplate);
		this.bindEvent("BtnCateAdd","click",jsHandler.addProcess);
	},
	
	run: function() {
		this.getPortletPlaceholder().drawToCanvas(this.render());
	}
}).implement(RenderInterface).implement(PortletInterface);


TemplateSearchPortletJSHandler = Class.extend(
		{			
			init: function(){
				this.keywords = new Array();
				this.defaultKws = new Array();
				this.defaultTags = new Array(); 
				this.kwCheck = new Array();
				this.choosenKwCheck = new Array();
			},
			
			initVars: function(){
				var objRet = null;
				var currentJsObj = this;
				var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
				
				$.ajax({url:root + 'ajax/get-keyword-search',success: function(ret){
					var keywordsRet = jQuery.parseJSON(ret);
					objRet = eval(keywordsRet.result);
				}, async: false});
				
				this.keywords = objRet;
				$.ajax({url:root + 'ajax/get-default-keyword-search',success: function(ret){
					var defaultKwsRet = jQuery.parseJSON(ret);
					objRet = eval(defaultKwsRet.result);
				},async:false});
				
				this.defaultKws = objRet;
				var i = -1;
				var length = this.keywords.length;
				
				var optionsEle = "";
				for (i=0; i<length; i++){
					optionsEle += "<option value='" + this.keywords[i]['keyword'] + "'>" + this.keywords[i]['content'] + "</option>";
				}
				$("#PltTemplateSearch-sltCategories").append(optionsEle);
				
				var length = this.defaultKws.length;
				
				var count = new Array();	
				for(i=0;i<length;i++){
					if(this.defaultTags[this.defaultKws[i]['tag']] == undefined){
						count[this.defaultKws[i]['tag']] = 0;
						this.defaultTags[this.defaultKws[i]['tag']] = new Array();
						this.defaultTags[this.defaultKws[i]['tag']] ['content'] = this.defaultKws[i]['tag_content'];
					}
					this.defaultTags[this.defaultKws[i]['tag']] [count[this.defaultKws[i]['tag']]] = new Array();
					this.defaultTags[this.defaultKws[i]['tag']] [count[this.defaultKws[i]['tag']]] ['keyword'] = this.defaultKws[i]['keyword'];
					this.defaultTags[this.defaultKws[i]['tag']] [count[this.defaultKws[i]['tag']]] ['content'] = this.defaultKws[i]['content'];
					count[this.defaultKws[i]['tag']] ++;
				}

				length = this.defaultTags.length;
				for (key in this.defaultTags){
					var objParam = {};
					objParam.tag = key;
					objParam.tag_content = this.defaultTags[key]['content'];
					var tmplx = $(tmpl("PltTemplateSearch-templatePlhld",objParam));
					$(tmplx).find("input[id^='PltTemplateSearch-input-']").bind('click',function(){
						currentJsObj.choosenKw(key, "PltTemplateSearch-input-" + key);
					});
					$("#PltTemplateSearch-templateHeading").append(tmplx);
				}	

				$("#PltTemplateSearch-templateHeading").children("div").each(function(){
						$(this).bind("mouseover",function(){currentJsObj.processTemplate($(this).attr("tag"));});
						$(this).bind("mouseout",function(){currentJsObj.hideTemplate($(this).attr("tag"));});
					});

				$("#PltTemplateSearch-templateContainer").hide();
				$("#PltTemplateSearch-templateContainerChosen").hide();
			},
			
			addProcess: function(){
				var currentJsObj = this;
				if(typeof this === 'object'){
					currentJsObj = SingletonFactory.getInstance(TemplateSearchPortletJSHandler);
				}
				
				var appendedChildren = $("<div></div>");
				var appendedUI = $("<div></div>");
				$("#PltTemplateSearch-sltCategories option:selected").each(function(){
					var kw = $(this).attr("value");
					var title = $(this).text();
					currentJsObj.addToCriteria(appendedChildren,kw,title);
					$(this).attr("disabled","disabled");
					$(this).removeAttr("selected");
					currentJsObj.addToToken(appendedUI,kw,title);
					currentJsObj.setKeywordOccupied(kw);
				});
				$("#PltTemplateSearch-divCriteria").append($(appendedChildren).children());
				$("#PltTemplateSearch-tokenContainer").append($(appendedUI).children());
			},
			
			isKeywordUsed: function(kw){
				if(this.kwCheck[kw] == undefined || this.kwCheck[kw] == false){
					return false;
				}
				return true;
			},

			setKeywordOccupied: function(kw){
				this.kwCheck[kw] = true;
			},

			unsetKeywordOccupied: function(kw){
				this.kwCheck[kw] = false;
			},

			addToCriteria: function(appendedChildren, kw, title){
				var currentJsObj = this;
				if(typeof this === 'object'){
					currentJsObj = SingletonFactory.getInstance(TemplateSearchPortletJSHandler);
				}
				var objParam = {};
				objParam.kw = kw;
				objParam.title = title;
				var tmplx = $(tmpl("PltTemplateSearch-criteriaPlhld",objParam));
				$(tmplx).children(".delToken").bind('click',function(){currentJsObj.delCriteria("PltTemplateSearch-div-"+kw)});
				$(appendedChildren).append(tmplx);
				return appendedChildren;
			},

			addToToken: function(appendedUI,kw,title){
				var objParam = {};
				objParam.kw = kw;
				objParam.content = title;
				var tmplx = $(tmpl("PltTemplateSearch-uitokenPlhld",objParam));
				$(appendedUI).append(tmplx);
				return appendedUI;
			},

			disableFromAvaiKw: function(kw){
				$("#PltTemplateSearch-sltCategories").children("option[value='"+kw+"']").attr("disabled","disabled");
				$("#PltTemplateSearch-sltCategories").children("option[value='"+kw+"']").removeAttr("selected");
			},

			delCriteria: function(id){
				if(confirm("Are you sure you want to remove this criterion?")){
					this.deleteProcess(id);
				}
			},

			deleteProcess: function(id){
				var kw = $("#" + id).children("input[id^=PltTemplateSearch-rule]").attr("kw");
				$("#PltTemplateSearch-sltCategories").find("option[value='"+ kw+"']").removeAttr("disabled");
				this.deleteToken("PltTemplateSearch-tokenContainer",kw);
				$("#" + id).remove();
				this.unsetKeywordOccupied(kw);
			},

			deleteToken: function(id,kw){
				$("#"+id).find("span[kw='"+kw+"']").remove();
			},

			searchCriteria: function(){
				var query = "";
				
				var currentJsObj = this;
				if(typeof this === 'object'){
					currentJsObj = SingletonFactory.getInstance(TemplateSearchPortletJSHandler);
				}
				var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
				
				$("#PltTemplateSearch-divCriteria").find("input[id^='PltTemplateSearch-rule']").each(function(){
					var content = $(this).val();
					var kw = $(this).attr("kw");
					kw += "_indexed";
					var partialContent = currentJsObj.processContent(kw, content);
					if($.trim(content) != ""){
						query += " OR " + partialContent;//kw + ":" + content;	
					}
				});
				query = query.substring(4);
				var ajaxUrl = root + "ajax/search-template/"; 
				$.ajax({url:ajaxUrl,data:{'search-query':query}, success: function(){
					//FIXME: Chuyển qua trang search result
					//console.log("Done ajaxing");
				}});
			},

			processContent: function(kw, content){
				var finalQuery = "";
				var regex = /\"(.+?)\"/;
				var phrases = new Array();
				var count = 0;
				donganh = content;
				while(regex.test(donganh)){
					var match = regex.exec(donganh);
					phrases[count++] = match[1].trim();
					donganh = donganh.replace(match[0], "");
				}

				//get words
				var words = new Array();
				words = donganh.split(/[ ]+/);
				
				for(i=0;i<count;i++){
					finalQuery += " " + kw + ":\"" + phrases[i] + "\"";
				}
				count = words.length;
				for(i=0;i<count;i++){
					if(words[i] == ""){
						continue;
					}
					finalQuery += " " + kw + ":" + words[i];
				}
				//return kw + ":" + content;
				return finalQuery.trim();
			},

			isEven: function(data){
				return data % 2 == 0;
			},

			checkUnCheckAll: function(){
				var checked = $("#PltTemplateSearch-CheckUnCheck").attr("checked");
				if(checked){
					$("input[id^='PltTemplateSearch-chkCriteria']").attr("checked","checked");
				} else {
					$("input[id^='PltTemplateSearch-chkCriteria']").removeAttr("checked");
				}
			},

			deleteAll: function(){
				var currentJsObj = this;
				if(typeof this === 'object'){
					currentJsObj = SingletonFactory.getInstance(TemplateSearchPortletJSHandler);
				}
				if(this.confirm("Are you sure you want to remove these criteria?")){
					$('input[id^="PltTemplateSearch-chkCriteria"]:checked').each(function(){
						currentJsObj.deleteProcess($(this).parent().attr("id"));
					});
					$("#PltTemplateSearch-CheckUnCheck").removeAttr("checked");
				}
			},

			resetCriteria: function(){
				if(confirm("Are you sure you want to reset these criteria?")){
					$('input[id^="PltTemplateSearch-chkCriteria"]:checked').each(function(){
						$(this).removeAttr("checked");
						$(this).prev().prev().val("");
					});
				}
			},

			initBody: function(){
//				$(document).ready(function(){
					this.initVars();
//				});
			},
			
			processTemplate: function(id){
				$("#PltTemplateSearch-templateContainer").empty();
				var length = this.defaultTags[id].length;
				var i=-1;
				for (i=0; i<length; i++){
					var kw = this.defaultTags[id][i]['keyword'];
					var title = this.defaultTags[id][i]['content'];
					var objParam = {};
					objParam.kw = kw;
					objParam.content = title;
					var tmplx = $(tmpl("PltTemplateSearch-uitokenPlhld",objParam));
					$("#PltTemplateSearch-templateContainer").append(tmplx);	
				}
				
				var offset =$("#PltTemplateSearch-templateHeading").children("div[tag='"+id+"']").offset(); 
				$("#PltTemplateSearch-templateContainer").attr("style","-moz-border-radius:10px; -moz-box-shadow:0 0 1px #111111; border: 1px solid #9DACCC; -webkit-border-radius:10px;-border-radius:10px; ;z-index:1000; position:absolute; width: 250px; min-height:240px; top:" + (offset.top-160) + "px; left: " + (offset.left + 50) + "px;") ;
				$("#PltTemplateSearch-templateContainer").next().attr("style","z-index:1000;visibility:visible; position:absolute; top:" + (offset.top-145) + "px; left: " + (offset.left + 40) + "px;").show();
				$("#PltTemplateSearch-templateContainer").show(500);
			},

			hideTemplate: function(id){
//				$("#templateContainer").empty();
				$("#PltTemplateSearch-templateContainer").hide();
				$("#PltTemplateSearch-templateContainer").next().hide();
			},


			addFromTemplate: function(tag){
				for ( var i = 0; i < this.defaultTags[tag].length; i++) {
					var kw = this.defaultTags[tag][i]["keyword"];
					if(this.isKeywordUsed(kw)){
						continue;
					}
					this.setKeywordOccupied(kw);
					var title = this.defaultTags[tag][i]["content"];
					this.addToToken($("#PltTemplateSearch-tokenContainer"), kw, title);
					this.addToCriteria($("#PltTemplateSearch-divCriteria"), kw, title);
					this.disableFromAvaiKw(kw);
				}
			},
			
			//var confirmTags = new Array();
			confirmAddFromTemplate: function(){
				var currentJsObj = this;
				if(typeof this === 'object'){
					currentJsObj = SingletonFactory.getInstance(TemplateSearchPortletJSHandler);
				}
				
				$("input[id^='PltTemplateSearch-input-']:checked").each(function(){
					var tag = $(this).attr("value");
//					if(confirmTags[tag] == undefined){
//						confirmTags[tag] = true;
					currentJsObj.addFromTemplate(tag);
//					}
				});
			},

			choosenKw: function(tag,id){
				if($("#" + id).is(":checked")){
					for ( var i = 0; i < this.defaultTags[tag].length; i++) {
						var kw = this.defaultTags[tag][i]["keyword"];
						var title = this.defaultTags[tag][i]["content"];
						if(this.choosenKwCheck[kw] == undefined || this.choosenKwCheck[kw] == 0){
							//them vao
							this.addToToken($("#PltTemplateSearch-templateContainerChosen"), kw, title);
							this.choosenKwCheck[kw] = 0;
						}
						this.choosenKwCheck[kw] ++;
					}
				} else {
					for ( var i = 0; i < this.defaultTags[tag].length; i++) {
						var kw = this.defaultTags[tag][i]["keyword"];
						var title = this.defaultTags[tag][i]["content"];
						this.choosenKwCheck[kw] --;
						if(this.choosenKwCheck[kw] == 0){
							this.deleteToken("PltTemplateSearch-templateContainerChosen",kw);
						}
					}
				}
//				$("#templateContainerChosen").show(500);
			}
		}
);